<template>
    <div>
        <el-form label-width="100">
            <el-form-item label="SPU名称">
                <el-input
                    placeholder="请输入SPU名称"
                    v-model="spuParams.spuName"
                ></el-input>
            </el-form-item>
            <el-form-item label="SPU品牌">
                <el-select v-model="spuParams.tmId">
                    <el-option
                        :label="item.tmName"
                        v-for="item in AllData"
                        :key="item.id"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input
                    type="textarea"
                    rows="2"
                    placeholder="请输入描述"
                    v-model="spuParams.description"
                ></el-input>
            </el-form-item>
            <el-form-item label="SPU图片">
                <el-upload
                    v-model:file-list="ImageList as UploadUserFile[]"
                    action="/api/admin/product/fileUpload"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                >
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="SPU销售属性">
                <el-select
                    v-model="SaleAttrIdAndName"
                    :placeholder="
                        unSaleAttr.length
                            ? `还有${unSaleAttr.length} 个未选择`
                            : '无'
                    "
                >
                    <el-option
                        :label="item.name"
                        v-for="item in unSaleAttr"
                        :key="item.id"
                        :value="`${item.id}:${item.name}`"
                    ></el-option>
                </el-select>
                <el-button
                    icon="Plus"
                    type="primary"
                    class="margin-left"
                    :disabled="!SaleAttrIdAndName"
                    @click="addSaleAttr"
                >
                    添加属性
                </el-button>
                <el-table border class="base-margin" :data="SaleAttr">
                    <el-table-column
                        label="序号"
                        type="index"
                        width="100"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        label="属性名"
                        width="100"
                        align="center"
                        prop="saleAttrName"
                    ></el-table-column>
                    <el-table-column label="属性值">
                        <template #="{ row, $index }">
                            <el-tag
                                @close="
                                    row.spuSaleAttrValueList.splice($index, 1)
                                "
                                v-for="item in row.spuSaleAttrValueList"
                                :key="item.id"
                                closable
                                class="margin-right"
                            >
                                {{ item.saleAttrValueName }}
                            </el-tag>
                            <el-input
                                @blur="toLook(row)"
                                v-model="row.saleAttrValue"
                                v-if="row.flag === true"
                                placeholder="请输入属性值"
                                style="width: 140px"
                            ></el-input>
                            <el-button
                                v-else
                                @click="toEdit(row)"
                                icon="Plus"
                                type="success"
                                size="small"
                                class="margin-left"
                            ></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" align="center">
                        <template #="{ row, $index }">
                            <el-button
                                type="danger"
                                icon="Delete"
                                size="small"
                                @click="SaleAttr.splice($index, 1)"
                            ></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save">保存</el-button>
                <el-button type="primary" @click="cancle">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import type {
    SpuDate,
    AllTradeMark,
    SpuPicData,
    BaseSaleAttrData,
    SaleAttrData,
    TradeMark,
    SpuPic,
    SaleAttr,
    BaseSaleAttr,
    SpuSaleAttr,
} from '@/api/product/spu/type';
import { ElMessage, type UploadUserFile } from 'element-plus';
import {
    reqAllTrademark,
    reqSpuPic,
    reqSpuSaleAttr,
    reqBaseSaleAttr,
    reqAddOrUpdateSpu,
} from '@/api/product/spu';
import { ref, computed } from 'vue';
const emit = defineEmits(['changeScenc']);
// 已有的 spu 数据
const AllData = ref<TradeMark[]>([]);
// 已有的 spu 图片数据
const ImageList = ref<SpuPic[]>([]);
// spu 基本的销售属性
const SaleAttr = ref<SaleAttr[]>([]);
// 所有的销售属性数据
const BaseSaleAttr = ref<BaseSaleAttr[]>([]);
const dialogVisible = ref<boolean>(false);
// 存储预览显示的图片地址
const dialogImageUrl = ref<string>('');
// 收集还未选择的属性 id 和 name
const SaleAttrIdAndName = ref<string>('');
const cancle = () => {
    emit('changeScenc', 0);
};
// 存储已有的 spu 对象
const spuParams = ref<SpuDate>({
    category3Id: '', //三级分类 id
    spuName: '', // spu 名字
    description: '', //描述
    tmId: '', //品牌 id
    spuImageList: [],
    spuSaleAttrList: [],
});

const initSpuForm = async (spu: SpuDate) => {
    spuParams.value = spu;
    // 获取全部品牌 数据
    const res: AllTradeMark = await reqAllTrademark();
    // 获取SPU图片
    const res1: SpuPicData = await reqSpuPic(spu.id as number);
    // 获取 spu 销售属性的数据
    const res2: SaleAttrData = await reqSpuSaleAttr(spu.id as number);
    // 获取 spu 本销售属性的数据
    const res3: BaseSaleAttrData = await reqBaseSaleAttr();
    // 将所有的数据融合
    AllData.value = res.data;
    ImageList.value = res1.data.map((item) => {
        return {
            name: item.imgName,
            url: item.imgUrl,
        };
    });
    SaleAttr.value = res2.data;
    BaseSaleAttr.value = res3.data;
};

// 查看预览图片时触发的函数
const handlePictureCardPreview = (fail: any) => {
    dialogVisible.value = true;
    dialogImageUrl.value = fail.url;
};
// 照片墙删除是触发的函数
const handleRemove = (fail: any) => {};
// 计算当前 spu 未拥有的销售属性
const unSaleAttr = computed(() => {
    return BaseSaleAttr.value.filter((item) => {
        return SaleAttr.value.every((item1) => {
            return item.name != item1.saleAttrName;
        });
    });
});
// 添加属性
const addSaleAttr = () => {
    const [baseSaleAttrId, saleAttrName] = SaleAttrIdAndName.value.split(':');
    const newSaleAttr: SaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
    };
    SaleAttr.value.push(newSaleAttr);
    SaleAttrIdAndName.value = '';
};
// 编辑属性
const toEdit = (row: SaleAttr) => {
    row.flag = true;
    row.saleAttrValue = '';
};
const toLook = (row: SaleAttr) => {
    // 收集属性 id 和属性名字
    const { baseSaleAttrId, saleAttrValue } = row;
    const newSaleAttrValue: SpuSaleAttr = {
        baseSaleAttrId,
        saleAttrValueName: saleAttrValue as string,
    };
    // 判断属性值是否为空
    if ((saleAttrValue as string).trim() == '') {
        ElMessage.warning('属性值不能为空');
        return;
    }

    // 判断属性值是否重复
    const isRepeat = row.spuSaleAttrValueList.some((item) => {
        return item.saleAttrValueName == newSaleAttrValue.saleAttrValueName;
    });
    if (isRepeat) {
        ElMessage.warning('属性值不能重复');
        return;
    }
    // 收集属性值
    row.spuSaleAttrValueList.push(newSaleAttrValue);
    row.flag = false;
};
// 保存
const save = async () => {
    // 整理照片墙的数据
    spuParams.value.spuImageList = ImageList.value.map((item: any) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url,
        };
    });
    // 整理 spu 销售属性的数据
    spuParams.value.spuSaleAttrList = SaleAttr.value;
    const res = await reqAddOrUpdateSpu(spuParams.value);
    if (res.code == 200) {
        ElMessage.success('成功');
        emit('changeScenc', 0);
    } else {
        ElMessage.error('失败');
    }
};
const initSpu = async (c3Id: any) => {
    // 清空数据
    Object.assign(spuParams.value, {
        category3Id: '', //三级分类 id
        spuName: '', // spu 名字
        description: '', //描述
        tmId: '', //品牌 id
        spuImageList: [],
        spuSaleAttrList: [],
    });
    // 收集三级分类 id
    spuParams.value.category3Id = c3Id;
    // 获取全部品牌 数据
    SaleAttr.value = [];
    ImageList.value = [];
    // 收集三级分类 id
    spuParams.value.category3Id = c3Id;
    const res: AllTradeMark = await reqAllTrademark();
    const res1: BaseSaleAttrData = await reqBaseSaleAttr();
    // 存储数据
    AllData.value = res.data;
    BaseSaleAttr.value = res1.data;
};
defineExpose({
    initSpuForm,
    initSpu,
});
</script>

<style>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.el-select {
    width: 200px;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
